package com.rgp.apipassenger.service.impl;

import com.rgp.internalcommon.common.RedisPrefixConstant;
import com.rgp.apipassenger.service.TokenRefreshService;
import com.rgp.apipassenger.utils.TokenCheckUtils;
import com.rgp.internalcommon.common.CommonStatusEnum;
import com.rgp.internalcommon.common.TokenDurationTimeConstant;
import com.rgp.internalcommon.dto.UserInfoDto;
import com.rgp.internalcommon.dto.ResponseResult;
import com.rgp.internalcommon.response.TokenResponse;
import com.rgp.internalcommon.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import java.util.concurrent.TimeUnit;

/**
 * @author nhp
 * @version 1.0
 * @description TODO
 * @date 2024-04-13 4:22
 */
@Service
public class TokenRefreshServiceImpl implements TokenRefreshService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public ResponseResult refreshToken(String refreshToken) throws Exception {
        //1.校验refreshToken的合法性 与 有效性【如果refreshToken 不合法 或 过期无效，那么让用户重新登录】
        if (!TokenCheckUtils.isValidToken(stringRedisTemplate,refreshToken)){
            return ResponseResult.fail(CommonStatusEnum.TOKEN_IS_NOT_VALID_ERROR);
        }

        //2.refreshToken合法且有效，那么重新生成双token返回给乘客
        UserInfoDto userInfoDto = JwtUtils.paseToken(refreshToken);

        //3.生成双token并存入到redis
        String accessToken = JwtUtils.tokenGenerate(userInfoDto, TokenDurationTimeConstant.ACCESS_TOKEN_VALID_MINUTES);
        refreshToken = JwtUtils.tokenGenerate(userInfoDto, TokenDurationTimeConstant.REFRESH_TOKEN_VALID_MINUTES);
        stringRedisTemplate.opsForValue().set(RedisPrefixConstant.PASSENGER_ACCESSTOKEN_PREFIX + userInfoDto.getUserPhone(),accessToken,TokenDurationTimeConstant.ACCESS_TOKEN_VALID_MINUTES, TimeUnit.MINUTES);
        stringRedisTemplate.opsForValue().set(RedisPrefixConstant.PASSENGER_REFRESHTOKEN_PREFIX + userInfoDto.getUserPhone(),refreshToken,TokenDurationTimeConstant.REFRESH_TOKEN_VALID_MINUTES,TimeUnit.MINUTES);

        //4.向用户颁发双token
        TokenResponse tokenResponse = new TokenResponse();
        tokenResponse.setAccessToken(accessToken);
        tokenResponse.setRefreshToken(refreshToken);
        return ResponseResult.success(tokenResponse);
    }
}